package errorx

import (
	"github.com/zeromicro/go-zero/core/logx"
	"github.com/zeromicro/go-zero/rest"
	"github.com/zeromicro/go-zero/rest/httpx"
	"google.golang.org/grpc/status"
	"net/http"
	"xialou_platform/app/respx"
)

/*
	type HTTPResponseInterceptor struct {
		writer      http.ResponseWriter
		wroteHeader bool
	}

	func NewHTTPResponseInterceptor(w http.ResponseWriter) *HTTPResponseInterceptor {
		return &HTTPResponseInterceptor{
			writer: w,
		}
	}

	func (i *HTTPResponseInterceptor) Write(body []byte) (int, error) {
		return i.writer.Write(body)
	}

	func (i *HTTPResponseInterceptor) Header() http.Header {
		return i.writer.Header()
	}

//WriteHeader override response WriteHeader

	func (i *HTTPResponseInterceptor) WriteHeader(statusCode int) {
		if i.wroteHeader {
			return
		}

		i.wroteHeader = true
		i.writer.WriteHeader(statusCode)
	}
*/
func JwtUnAuthorizedHandle() rest.RunOption {
	return rest.WithUnauthorizedCallback(func(w http.ResponseWriter, r *http.Request, err error) {
		logx.Info("===========jwt=WithUnauthorizedCallback=====================")
		httpx.Error(w, NewMsgCodeError(UnLoginCode, "请登录"))
	})
}

func ErrHandle(err error) (int, interface{}) {
	switch e := err.(type) {
	case *CodeError:
		return http.StatusOK, e.DataInfo()
	default:
		st, ok := status.FromError(err)
		if ok {
			return http.StatusOK, &respx.Response{
				Code:    int(st.Code()),
				Message: st.Message(),
				Data:    nil,
				Reason:  err.Error(),
			}
		}
		return http.StatusOK, &respx.Response{
			Code:    10001,
			Message: "server error",
			Data:    nil,
			Reason:  err.Error(),
		}
	}
}

/*
func(err error) (int, interface{}) {
		switch e := err.(type) {
		case *errorx.CodeError:
			return http.StatusOK, e.DataInfo()
		default:
			st, ok := status.FromError(err)
			if ok {
				//if st.Code() != errorx.NotFoundResourceCode {
				//	return errorx.NewUnknownError(err.Error())
				//}
				return http.StatusOK, &respx.Response{
					Code:    int(st.Code()),
					Message: st.Message(),
					Data:    nil,
					Reason:  err.Error(),
				}
			}
			return http.StatusOK, &respx.Response{
				Code:    10001,
				Message: "server error",
				Data:    nil,
				Reason:  err.Error(),
			}
		}
	}
*/
